package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.Neusoft.vo.ImportDeleteSecurityVo;
import com.zhangtai.exception.RException;
import com.zhangtai.modules.constVo.CredentialConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.dao.EmployeeSecurityDao;
//import com.zhangtai.modules.dao.ssqlDao.JobDaoMssql;
import com.zhangtai.modules.dto.AwardInfoExportDto;
import com.zhangtai.modules.dto.SubsidyExportDto;
import com.zhangtai.modules.entity.credential.CredentialHangEntity;
import com.zhangtai.modules.entity.credential.CredentialInfoEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.EmployeeSecurityEntity;
import com.zhangtai.modules.entity.salary.ComputerSubsidyEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.credential.CredentialHangService;
import com.zhangtai.modules.service.credential.CredentialInfoService;
import com.zhangtai.modules.service.salary.ComputerSubsidyService;
import com.zhangtai.modules.vo.EmployeeSecurityVo;
import com.zhangtai.modules.vo.ImportCredentialVo;
import com.zhangtai.modules.vo.ImportSecurityExcelVo;
import com.zhangtai.modules.vo.ImportSecurityVo;
import com.zhangtai.utils.*;
import com.zhangtai.utils.DateUtils;
import com.zhangtai.utils.Excel.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("import")
@Slf4j
@Api(tags = "表单导入接口")
public class ImportController {

    @Autowired
    private SecurityController securityController;
    @Autowired
    private BaseMssqlServiceImpl baseMssqlService;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private EmployeeSecurityDao employeeSecurityDao;
    @Autowired
    private LoginController loginController;
    @Autowired
    private CredentialInfoService credentialInfoService;
    @Autowired
    private CredentialHangService credentialHangService;
//    @Autowired
//    private JobDaoMssql jobDaoMssq;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private ComputerSubsidyService computerSubsidyService;
    @Autowired
    private JobController jobController;


    @PostMapping("/importEmployeeSecurity")
    @ApiOperation("/社保人员导入")
    public R importEmployeeSecurity(ImportSecurityExcelVo excelVo, HttpServletRequest request)throws Exception{
        boolean isError = true;
        int successNum =0;
        int errorNum = 0;
        List<String> errorMsg = new ArrayList<>();
        List<String> handleMsg = new ArrayList<>();
        Date date = new Date();
        for (MultipartFile multipartFile : excelVo.getFile()) {
            String filename = multipartFile.getOriginalFilename();
            if(!filename.endsWith(".xlsx")) {
                return R.error("导入数据出错：上传的文件类型出错");
            }
            R r = ExcelUtil.importBaseExcel(multipartFile, 2, ImportSecurityVo.class);

            if(r.getFlag()) {
                List<ImportSecurityVo> voList = (List<ImportSecurityVo>) r.getData();
                for(ImportSecurityVo importVo:voList){
                    EmployeeSecurityVo vo = BeanUtilsMabach.doToDto(importVo,EmployeeSecurityVo.class);
                    if(!StringUtils.isEmpty(importVo.getUnemploymentInsurance()))
                    vo.setUnemploymentInsurance(new BigDecimal(importVo.getUnemploymentInsurance()));
                    if(!StringUtils.isEmpty(importVo.getDisabledEmployment()))
                    vo.setDisabledEmployment(new BigDecimal(importVo.getDisabledEmployment()));
                    if(!StringUtils.isEmpty(importVo.getMaternityInsurance()))
                    vo.setMaternityInsurance(new BigDecimal(importVo.getMaternityInsurance()));
                    if(!StringUtils.isEmpty(importVo.getLargerMedical()))
                    vo.setLargerMedical(new BigDecimal(importVo.getLargerMedical()));
                    if(!StringUtils.isEmpty(importVo.getInjuryInsurance()))
                    vo.setInjuryInsurance(new BigDecimal(importVo.getInjuryInsurance()));
                    if(!StringUtils.isEmpty(importVo.getEndowmentInsurance()))
                    vo.setEndowmentInsurance(new BigDecimal(importVo.getEndowmentInsurance()));
                    if(!StringUtils.isEmpty(importVo.getMedicalInsurance()))
                        vo.setMedicalInsurance(new BigDecimal(importVo.getMedicalInsurance()));
                    if(!StringUtils.isEmpty(importVo.getOfferFunds()))
                        vo.setOfferFunds(new BigDecimal(importVo.getOfferFunds()));
                    if(!StringUtils.isEmpty(importVo.getReservedFunds()))
                        vo.setReservedFunds(new BigDecimal(importVo.getReservedFunds()));
                    if(ObjectUtils.isEmpty(vo.getCode())){
                        isError = false;
                        handleMsg.add( "工号："+vo.getName()+"工号为空的员工不存在无法录入！");
                        errorNum++;
                        continue;
                    }
                    EmployeeInfoEntity infoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code",vo.getCode()).eq("is_delete",0));
                   if(ObjectUtils.isEmpty(infoEntity)){
                       infoEntity = baseMssqlService.finEmpFromMssqlByCode(vo.getCode());
                   }
                    if(!ObjectUtils.isEmpty(infoEntity)){
                        vo.setOid(infoEntity.getOid());
                    }
                    if(ObjectUtils.isEmpty(infoEntity)){
                        isError = false;
                        handleMsg.add( "姓名："+vo.getName()+",工号："+vo.getCode()+"的员工不存在无法录入！");
                        errorNum++;
                        continue;
                    }
                    vo.setTypeId(Long.parseLong(excelVo.getTypeId()));
                    vo.setType(excelVo.getType());
                    R save = securityController.saveOrUpdateEmployeeSecurity(vo,request,excelVo.getIsUpdate() == 1);
                    if(!save.getFlag()){
                        isError = false;
                        handleMsg.add("姓名："+vo.getName()+",工号:"+vo.getCode()+","+save.getError());
                        errorNum++;
                    }else{
                        successNum++;
                    }
                }
            }
        }
        Date date2 = new Date();
        log.info("社保批量导入耗时-----------》{}秒",(date2.getTime()-date.getTime())/1000);
        errorMsg.add("导入成功条数："+successNum+"，导入失败条数："+errorNum);
        if(!isError){
            errorMsg.addAll(handleMsg);
        }
        return  R.ok(errorMsg);
    }



    @PostMapping("/uploadFile")
    @ApiOperation(value = "导入奖罚分配人员")
    public R uploadAward(@RequestParam("file") MultipartFile file , @RequestParam(value = "type",defaultValue = "1") Integer type)  {
        if (file==null) {
            throw new RException("上传文件不能为空");
        }
        R r= ExcelUtil.importBaseExcel(file,0, AwardInfoExportDto.class);
        return r;
    }

    @PostMapping("/uploadFileSubsidy")
    @ApiOperation(value = "导入电脑补贴")
    @Transactional
    public R uploadFileSubsidy(@RequestParam("file") MultipartFile file)  {
        if (file==null) {
            throw new RException("上传文件不能为空");
        }
        R r=  ExcelUtil.importBaseExcel(file,1, SubsidyExportDto.class);
        List<SubsidyExportDto> subsidyExportDtoList =(List<SubsidyExportDto>)r.getData();
        if(!CollectionUtils.isEmpty(subsidyExportDtoList)){
            for (SubsidyExportDto subsidyExportDto:subsidyExportDtoList){
                ComputerSubsidyEntity computerSubsidyEntity = BeanUtilsMabach.doToDto(subsidyExportDto, ComputerSubsidyEntity.class);
                computerSubsidyEntity.setApplyMode(2);
                computerSubsidyEntity.setMonthlyAmount(new BigDecimal(subsidyExportDto.getMonthlyAmount()));
                switch (subsidyExportDto.getTypeStr()){
                    case "电脑补贴":
                        computerSubsidyEntity.setType(1);
                        if(!StringUtils.isEmpty(subsidyExportDto.getInvoicePrice()))
                        computerSubsidyEntity.setInvoicePrice(new BigDecimal(subsidyExportDto.getInvoicePrice()));
                        if("普通岗位".equals(subsidyExportDto.getPostTypeStr())){
                            computerSubsidyEntity.setPostType(0);
                        }else{
                            computerSubsidyEntity.setPostType(1);
                        }
                        break;
                    case "住房补贴":
                        computerSubsidyEntity.setType(2);
                        break;
                    case "异地补贴":
                        computerSubsidyEntity.setType(3);
                        break;
                    case "其他补贴":
                        computerSubsidyEntity.setType(4);
                        break;
                }
             List<EmployeeInfoEntity> employeeInfoEntityList=  employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("code",computerSubsidyEntity.getCode())
                        .eq("is_delete",0));
                if(CollectionUtils.isEmpty(employeeInfoEntityList)){
                    ComputerSubsidyEntity entity=computerSubsidyEntity;
                }
                EmployeeInfoEntity employeeInfoEntity= employeeInfoEntityList.get(0);
                computerSubsidyEntity.setOid(employeeInfoEntity.getOid());
                computerSubsidyEntity.setOrgId(employeeInfoEntity.getOrgId());
                computerSubsidyEntity.setUnitId(employeeInfoEntity.getUnitId());
                computerSubsidyEntity.setJobId(employeeInfoEntity.getJobId());
                computerSubsidyEntity.setApplyDate(new Date());
                computerSubsidyEntity.setApproveStatus(2);
               // computerSubsidyEntity.setJobName(jobController.getJobName(employeeInfoEntity.getJobId()));
               // computerSubsidyEntity.setOrgName(jobController.getOrgNameById(employeeInfoEntity.getOrgId()));
               // computerSubsidyEntity.setUnitName(jobController.getOrgNameById(employeeInfoEntity.getUnitId()));
                computerSubsidyEntity.setDuration(DateUtils.monthsBetween(computerSubsidyEntity.getStartDate(),computerSubsidyEntity.getEndDate()));
                computerSubsidyService.saveE(computerSubsidyEntity);
            }
        }
        return R.ok();
    }


    @PostMapping("/importDeleteEmployeeSecurity")
    @ApiOperation("/社保人员批量删除导入")
    public R importDeleteEmployeeSecurity(ImportSecurityExcelVo excelVo,HttpServletRequest request)throws Exception{
        boolean isError = true;
        int successNum =0;
        int errorNum = 0;
        List<String> errorMsg = new ArrayList<>();
        List<String> handleMsg = new ArrayList<>();
        for (MultipartFile multipartFile : excelVo.getFile()) {
            String filename = multipartFile.getOriginalFilename();
            if(!filename.endsWith(".xlsx")) {
                return R.error("导入数据出错：上传的文件类型出错");
            }
            R r = ExcelUtil.importBaseExcel(multipartFile, 2, ImportDeleteSecurityVo.class);
            if(r.getFlag()) {
                List<ImportDeleteSecurityVo> list = (List<ImportDeleteSecurityVo>) r.getData();
                for(ImportDeleteSecurityVo vo:list){
                    EmployeeInfoEntity infoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code",vo.getCode()).eq("is_delete",0));
                    if(ObjectUtils.isEmpty(infoEntity)){
                        infoEntity = baseMssqlService.finEmpFromMssqlByCode(vo.getCode());
                    }
                    if(ObjectUtils.isEmpty(infoEntity)){
                        isError = false;
                        handleMsg.add( "姓名："+vo.getName()+",工号："+vo.getCode()+"的员工不存在无法删除！");
                        errorNum++;
                        continue;
                    }
                    EmployeeSecurityEntity one = employeeSecurityDao.selectOne(new QueryWrapper<EmployeeSecurityEntity>().eq("id_delete",0).eq("oid",infoEntity.getOid()));
                    if(ObjectUtils.isEmpty(one)){
                        isError = false;
                        handleMsg.add( "姓名："+vo.getName()+",工号："+vo.getCode()+"的员工未分配社保方案无法删除！");
                        errorNum++;
                        continue;
                    }
                    securityController.deleteEmployeeSecurity(excelVo.getType(),one.getId().toString(),excelVo.getTypeId(),infoEntity.getOid().toString(),request);
                    successNum++;
                }
            }
        }

        errorMsg.add("导入成功条数："+successNum+"，导入失败条数："+errorNum);
        if(!isError){
            errorMsg.addAll(handleMsg);
        }
        return  R.ok(errorMsg);
    }

    @PostMapping("/importCredentialInfo")
    @ApiOperation("/资质挂证导入")
    public R importCredentialInfo(@RequestParam("file") MultipartFile file,HttpServletRequest request)throws Exception{
        JSONObject object = loginController.getUserInfo(request).getData();
        String userCode = object.getString("usercode");
        String filename = file.getOriginalFilename();
        boolean isError = true;
        int successNum =0;
        int errorNum = 0;
        List<String> errorMsg = new ArrayList<>();
        List<String> handleMsg = new ArrayList<>();
        Map<String,Long> orgMap = new HashMap<>();
        Date date = new Date();
        if(!filename.endsWith(".xlsx")) {
            return R.error("导入数据出错：上传的文件类型出错");
        }
        R r = ExcelUtil.importBaseExcel(file, 2, ImportCredentialVo.class);
        if(r.getFlag()) {
            List<ImportCredentialVo> list = (List<ImportCredentialVo>) r.getData();
            for(ImportCredentialVo vo:list){
                EmployeeInfoEntity infoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code",vo.getCode()).eq("is_delete",0));
                if(ObjectUtils.isEmpty(infoEntity)){
                    infoEntity = baseMssqlService.finEmpFromMssqlByCode(vo.getCode());
                }
                if(ObjectUtils.isEmpty(infoEntity)){
                    isError = false;
                    handleMsg.add( "姓名："+vo.getName()+",工号："+vo.getCode()+"的员工不存在无法删除！");
                    errorNum++;
                    continue;
                }
                CredentialInfoEntity entity = BeanUtilsMabach.doToDto(vo,CredentialInfoEntity.class);
                entity.setHangStatus(CredentialConst.HANG_STATUS_CHECKED);
                entity.setCreateTime(date);
                entity.setStatus(1);
                entity.setOid(infoEntity.getOid());

                entity.setEndTime(vo.getEndTime());
                if(StringUtils.isEmpty(vo.getIsAudit())){
                    entity.setIsAudit(0);
                }else if("是".equals(vo.getIsAudit())){
                    entity.setIsAudit(1);
                }else{
                    entity.setIsAudit(0);
                }

                entity.setStartTime(vo.getStartTime());
                //处理挂靠公司
                if(ObjectUtils.isEmpty(orgMap.get(vo.getUnitName()))&&!StringUtils.isEmpty(vo.getUnitName())){
//                   List<Long> orgId =  jobDaoMssq.findOrgByName(vo.getUnitName());
//                   if(!CollectionUtils.isEmpty(orgId)){
//                       orgMap.put(vo.getUnitName(),orgId.get(0));
//                       entity.setUnitId(orgId.get(0));
//                   }
                }else{
                    entity.setUnitId(orgMap.get(vo.getUnitName()));
                }

                credentialInfoService.saveE(entity);
                CredentialHangEntity hangEntity = new CredentialHangEntity();
                hangEntity.setStatus(CredentialConst.HANG_STATUS_CHECKED);
                hangEntity.setApplierCode(userCode);

                hangEntity.setAllowanceTime(vo.getAllowanceTime());
                hangEntity.setIsDelete(0);
                hangEntity.setReason(vo.getReason());
                hangEntity.setCreateTime(date);
                if(!StringUtils.isEmpty(vo.getAllowance()))
                hangEntity.setAllowance(new BigDecimal(vo.getAllowance()));
                hangEntity.setCredentialId(entity.getId());
                hangEntity.setId(snowflakeIdWorker.nextId());
                credentialHangService.saveE(hangEntity);
            }
        }
        errorMsg.add("导入成功条数："+successNum+"，导入失败条数："+errorNum);
        if(!isError){
            errorMsg.addAll(handleMsg);
        }
        return  R.ok(errorMsg);
    }
}
